// 获取产线配置记录ID
var lineCode = getQueryString("lineCode");
$(function () {
    //区块锁定标识
    var lock = false;
    //加载layer拓展
    layer.config({
        extend: './extend/layer.ext.js'
    });
    //右键菜单参数
    context.init({
        fadeSpeed: 100,
        filter: function ($obj) {
        },
        above: 'auto',
        preventDoubleContext: true,
        compress: false
    });

    //创建拖拽方法
    $("#canvas").mousedown(function(e){
        var canvas = $(this);
        e.preventDefault();
        var pos = $(this).position();
        this.posix = {'x': e.pageX - pos.left, 'y': e.pageY - pos.top};
        $.extend(document, {'move': true, 'move_target': this, 'call_down' : function(e, posix){
                canvas.css({
                    'cursor': 'move',
                    'top': e.pageY - posix.y,
                    'left': e.pageX - posix.x
                });
            }, 'call_up' : function(){
                canvas.css('cursor', 'default');
            }}
        );
    }).on('mousedown', '.box', function(e) {
        if(lock) return;
        var pos = $(this).position();
        // 记录下偏移量
        this.posix = {'x': e.pageX - pos.left, 'y': e.pageY - pos.top};
        var pyX = e.pageX - pos.left;
        var pyY = e.pageY - pos.top;
        $.extend(document,
            {
                'move': true,
                'move_target': this,
                'call_up' : function(e){
                    // 设置x,y
                    vm.devDetail.pagex = e.pageX - pyX;
                    vm.devDetail.pagey = e.pageY - pyY;
                }
            }
        );
        e.stopPropagation();

    }).on('mousedown', '.box .coor', function(e) {
        var $box = $(this).parent();
        var posix = {
            'w': $box.width(),
            'h': $box.height(),
            'x': e.pageX,
            'y': e.pageY
        };
        var pyX = e.pageX - $box.width();
        var pyY = e.pageY - $box.height();
        $.extend(document,
            {
                'move': true,
                'call_down': function(e) {
                    $box.css({
                        'width': Math.max(30, e.pageX - posix.x + posix.w),
                        'height': Math.max(30, e.pageY - posix.y + posix.h)
                    });
                },
                'call_up' : function(e){
                    // 设置x,y
                    vm.devDetail.width = e.pageX - pyX;
                    vm.devDetail.height = e.pageY - pyY;
                }
            }
        );
        e.stopPropagation();
    });
    // 初始化单击事件
    $("#canvas").dblclick(function (e) {
        vm.devDetail = {
            code: '',
            width: 100,
            height: 100,
            pagex: e.pageX,
            pagey: e.pageY,
            alarmThreshold:0 // 设备报警阈值
        };
        vm.lineSettedDevList.push(vm.devDetail);
    });
    // 直接加载工序设备
    vm.loadStationDev();
});
var vm = new Vue({
    el: "#rrapp",
    data: {
        visible: false,
        yzh: '',
        devDetail:{
            code: '',
            width: 100,
            height: 100,
            pagex: 0,
            pagey: 0,
            alarmThreshold:0 // 设备报警阈值
        },
        lineCode: getQueryString("lineCode"), // 当前产线码
        lineSettingId: '', // 产线配置ID
        lineSettingUrl: '', // 产线平面图地址
        deviceList: [], // 关联到某工序的设备列表，下拉框
        lineSettedDevList:[], // 产线下已设置的设备列表
    },
    methods: {
        // 加载某工序下关联到的设备
        loadStationDev: function () {
            Ajax.request({
                url: "../deviceinfo/getByStationCode?deptCode=" + lineCode,
                async: false,
                successCallback: function (r) {
                    vm.deviceList = r.deviceList;
                }
            });
        },
        // 加载当前产线下已设置的设备位置信息
        loadSettedLineDevList: function () {
            var _this = this;
            // 重新加载数据
            Ajax.request({
                url: "../devPlane/devCoorSetting?lineCode=" + _this.lineCode,
                type: 'GET',
                async: false,
                contentType: "application/json",
                successCallback: function (r) {
                    if (r.code == 0) {
                        _this.lineSettedDevList = r.lineDevCoorSetting;
                    } else {
                        iview.Message.error(r.msg);
                    }
                }
            });
        },
        // 渲染设备坐标
        renderDeviceCoor: function () {
            var _this = this;
            // 清空当前页面设备状态
            $('.box').remove();
            // 重新渲染
            for (var idx = 0; idx < this.lineSettedDevList.length; idx++) {
                var data = this.lineSettedDevList[idx];
                var value = data.code || '';
                var color = 'rgb(0, 128, 0)';
                var height = data.height || 0;
                var width = data.width || 0;
                var pageX = data.pagex || 0;
                var pageY = data.pagey || 0;
                //创建区域块
                var pos = $("#canvas").position();
                var box = $('<div class="box" id="' + idx + '"><pre class="content">' + value + '</pre><div class="bg transparent" style="background-color:' + color + '"></div><div class="coor transparent"></div></div>').css({
                    width: width,
                    height: height,
                    top: pageY > 0 ? pageY : (pos.top > 0 ? 0 : pos.top * -1 + 50),
                    left: pageX > 0 ? pageX : (pos.left > 0 ? 0 : pos.left * -1 + 30)
                }).appendTo("#canvas");
                //计算文本位置
                box.find('.content').css({
                    marginLeft: box.find('.content').width() / 2 * -1,
                    marginTop: box.find('.content').height() / 2 * -1
                });
            }
            // 然后给每个 li 加菜单
            $(".box[id]").each(function() {
                var id = $(this).prop("id");
                _this.attachContext("#" + id);
            })
        },
        // 写个 builder 函数
        attachContext:function(selector) {
            //创建右键菜单
            context.attach(selector,
                [
                    {header: '操作'},
                    {
                        text: '编辑区域',
                        action: function (e) {
                            e.preventDefault();
                            vm.visible = true;
                            openWindow({
                                title: "设备信息维护",
                                area: ['400px', '260px'],
                                content: jQuery("#addScheduleDiv"),
                                btn: ['确定', '取消'],
                                btn1: function (index) {
                                    // 设置产线配置ID
                                    vm.devDetail.pid = vm.lineSettingId;
                                    // 获取当前设备信息
                                    Ajax.request({
                                        url: "../devlinedevcoordinate/dev/save",
                                        params: JSON.stringify(vm.devDetail),
                                        type: "POST",
                                        contentType: "application/json",
                                        successCallback: function (r) {
                                            alert('操作成功', function (index) {
                                                vm.renderDeviceCoor()
                                                layer.closeAll()
                                            });
                                        }
                                    });
                                }
                            });

                        }
                    },
                    {
                        text: '删除区域',
                        action: function (e) {
                            e.preventDefault();
                            // 获取当前点击的设备信息
                            var devIdx = parseInt($(selector).attr('id'));
                            var devSetting = vm.lineSettedDevList[devIdx];
                            //此处做提交异步方法，往数据库提交删除请求
                            confirm('确定要删除选中信息?', function () {
                                // 获取当前设备信息
                                Ajax.request({
                                    url: "../devlinedevcoordinate/dev/delete?id=" + devSetting.id,
                                    async: true,
                                    successCallback: function () {
                                        alert('操作成功', function (index) {
                                            vm.lineSettedDevList.splice(devIdx,1);
                                        });
                                    }
                                });
                            });
                        }
                    }
                ]
            );
        },
        // 全屏设置
        toggleFullScreen: function () {
            if (!document.fullscreenElement && // alternative standard method
                !document.mozFullScreenElement && !document.webkitFullscreenElement) {// current working methods
                if (document.documentElement.requestFullscreen) {
                    document.documentElement.requestFullscreen();
                } else if (document.documentElement.mozRequestFullScreen) {
                    document.documentElement.mozRequestFullScreen();
                } else if (document.documentElement.webkitRequestFullscreen) {
                    document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
                }
            } else {
                if (document.cancelFullScreen) {
                    document.cancelFullScreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitCancelFullScreen) {
                    document.webkitCancelFullScreen();
                }
            }
        },
        // 返回列表页
        backForward: function () {
            history.go(-1);
        }
    },
    created() {
        var _this = this;
        // 获取当前设备信息
        Ajax.request({
            url: "../devlinedevcoordinate/info?lineCode=" + _this.lineCode,
            async: true,
            successCallback: function (r) {
                _this.lineSettingId = r.lineCoorSet.id;
                _this.lineSettingUrl = r.lineCoorSet.url;
            }
        });
        // 刷新当前页面
        this.loadSettedLineDevList();
    },
    watch:{
        lineSettedDevList: function (newList,oldList) {
            this.renderDeviceCoor();
        }
    }
})
